package by.semerikov.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.semerikov.converter.ProposalConverter;
import by.semerikov.dao.DAOFactory;
import by.semerikov.dao.IProposalDAO;
import by.semerikov.data.Connector;
import by.semerikov.entity.ProposalEntity;
import by.semerikov.exceptions.ConnectorException;
import by.semerikov.exceptions.DAOException;
import by.semerikov.model.Proposal;

public class ProposalService {
	
	ProposalConverter proposalConverter  = new ProposalConverter();
 
	public void createProposal(Proposal object) throws DAOException, ConnectorException
	{
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IProposalDAO prd = DAOFactory.getInstance().getProposalDAO();
			prd .setConnection(conn);
			prd.create(proposalConverter.convertToEntity(object));
			conn.setAutoCommit(true);
			conn.close();
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.proposal.create",e);
		}
	}
	
	public List<Proposal> getProposal(Proposal example) throws DAOException, ConnectorException
	{
		List<Proposal> result = new ArrayList<Proposal>();
		List<ProposalEntity> resultEntity = new ArrayList<ProposalEntity>();
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IProposalDAO pd = DAOFactory.getInstance().getProposalDAO();
			pd.setConnection(conn);
			resultEntity = pd.read(proposalConverter.convertToEntity(example));
			for (int i = 0; i < resultEntity.size(); i++) {
				result.add(proposalConverter.convertToModel(resultEntity.get(i), conn));
			}
			conn.setAutoCommit(true);
			conn.close();
			
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.proposal.read",e);
		}
		return result;
		
	}
	
	public void deleteProposal(Proposal object) throws DAOException
	{
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IProposalDAO prd = DAOFactory.getInstance().getProposalDAO();
			prd .setConnection(conn);
			prd.delete(proposalConverter.convertToEntity(object));
			conn.setAutoCommit(true);
			conn.close();
		} catch (Exception e) {
			throw new DAOException("exception.service.proposal.delete",e);
		}
	}
	
	public void updateProposal(Proposal object) throws DAOException, ConnectorException
	{
		try {
			Connection conn = Connector.getConnection();
			conn.setAutoCommit(false);
			IProposalDAO prd = DAOFactory.getInstance().getProposalDAO();
			prd .setConnection(conn);
			prd.update(proposalConverter.convertToEntity(object)); 
			conn.setAutoCommit(true);
			conn.close();
		} catch (SQLException e) {
			throw new ConnectorException("exception.service.proposal.update",e);
		}
	}
	
}
